import { getConfigure } from './configure';

// 获取默认配置
const defaultConfig = getConfigure();
// 固定前缀，以区分不同项目
const keyPrefix = ()=> defaultConfig.deployDirectory !== '/' ? defaultConfig.deployDirectory : '';

// 生成特使key值,不同页面、同一个页面多个
const specialKey = key => {
  const { pathname } = window.location;
  const userId = localStorage.getItem(`${keyPrefix()}userId`) || '';
  return `${pathname}-${userId}-${key}`;
};
const setItem = (key, val, isSpecial = false) => {
  const tempKey = isSpecial ? specialKey(key) : keyPrefix() + key;
  const tempVal = typeof val === 'object' ? JSON.stringify(val) : val;
  localStorage.setItem(tempKey, tempVal);
};
const getItem = (key, isSpecial = false, needParse = false) => {
  const tempKey = isSpecial ? specialKey(key) : keyPrefix() + key;
  let res = localStorage.getItem(tempKey);
  if (needParse) {
    try {
      res = JSON.parse(res);
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log(error);
    }
  }
  return res;
};
const removeItem = (key, isSpecial) => {
  localStorage.removeItem(isSpecial ? specialKey(key) : keyPrefix() + key);
};

export default {
  setItem,
  getItem,
  removeItem,
};
